﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml;
using System.Xml.Linq;

namespace WeSpot.Models
{
    public static class BadgeUtils
    {
        /// <summary>
        /// GetBadge
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        private static string GetBadge(string uri)
        {
            // build the request url with the tableName appended to the end.
            WebRequest request = WebRequest.Create(uri);

            // use the GET method.
            request.Method = "GET";
            request.Headers["Authorization"] = Properties.Settings.Default.BadgeApiKey;

            // create a web response
            WebResponse response = request.GetResponse();

            // create a data stream.
            Stream dataStream = response.GetResponseStream();

            // create a stream reader.
            StreamReader reader = new StreamReader(dataStream);

            // read the content into a string
            string ret = reader.ReadToEnd();

            reader.Close();
            dataStream.Close();
            response.Close();

            return ret;
        }

        /// <summary>
        /// PostBadge
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        private static string PostBadge(string uri, string json)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.ContentType = "application/json";
            request.Method = "POST";
            //request.Headers["Accept"] = "application/json";
            request.Headers["Authorization"] = Properties.Settings.Default.BadgeApiKey;

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
            {
                return streamReader.ReadToEnd();
            }
        }

        /// <summary>
        /// JsonToObject
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static BadgeJsonModels.Rootobject JsonToBadgeJsonObject(string json)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            BadgeJsonModels.Rootobject root = jss.Deserialize<BadgeJsonModels.Rootobject>(json);
            return root;
        }

        /// <summary>
        /// Convert json string to XmlDocument
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static XmlDocument JsonToXML(string json)
        {
            XmlDocument doc = new XmlDocument();

            using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
            {
                XElement xml = XElement.Load(reader);
                doc.LoadXml(xml.ToString());
            }

            return doc;
        }

        /// <summary>
        /// GetBadgeByContext
        /// </summary>
        /// <param name="inquiryId"></param>
        /// <returns></returns>
        public static string GetBadgeByContext(string inquiryId)
        {
            string url = Properties.Settings.Default.BadgeUrl + "context/" + inquiryId;

            return GetBadge(url);
        }

        /// <summary>
        /// GetBadgeByIdentifier
        /// </summary>
        /// <param name="badgeId"></param>
        /// <returns></returns>
        public static string GetBadgeByIdentifier(string badgeId)
        {
            string url = Properties.Settings.Default.BadgeUrl + "badgeIdentifier/" + badgeId;

            return GetBadge(url);
        }

        /// <summary>
        /// GetAwardByBadgeId
        /// </summary>
        /// <param name="badgeId"></param>
        /// <returns></returns>
        public static string GetAwardByBadgeId(string badgeId)
        {
            string url = Properties.Settings.Default.BadgeUrl + "badgeId/" + badgeId + "/awarded";

            return GetBadge(url);
        }
        
        /// <summary>
        /// GetAwardByUser
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="oauthid"></param>
        /// <returns></returns>
        public static string GetAwardByUser(string provider, string oauth)
        {
            string url = Properties.Settings.Default.BadgeUrl + "user/" + provider + "_" + oauth + "/awarded";

            return GetBadge(url);
        }

        /// <summary>
        /// PostCreateAward
        /// </summary>
        /// <param name="badgeid"></param>
        /// <param name="provider"></param>
        /// <param name="oauth"></param>
        /// <param name="Evidence"></param>
        /// <returns></returns>
        public static string PostCreateBadgeAward(string badgeid, string provider, string oauth, string Evidence)
        {
            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
            {
                badgeId = badgeid,
                recipient = provider + "_" + oauth, // check this ???
                evidence = Evidence
            });

            string uri = @"" + Properties.Settings.Default.BadgeUrl + "badgeId/" + badgeid + "/award";

            return PostBadge(uri, json);
        }

    }
}